//
//  ComfirnDeatilController.m
//  Runone
//
//  Created by runone02 on 16/11/23.
//  Copyright © 2016年 runone. All rights reserved.
//  未开始

#import "ComfirnDeatilController.h"
#import "RequestGinsengModel.h"
#import "RequestHelper.h"
#import "EventDetailModel.h"
#import "MJExtension.h"
#import "SVProgressHUD.h"
#import "ConEventDetailInfo.h"
#import "EventDealList.h"
#import "ParModel.h"
#import "DrowDownViewController.h"
#import "AppDelegate.h"
#import "HighwayMergeRoadRecordModel.h"
#import "DropDownBackView.h"
#import "UIView+Common.h"
#import "DateViewController.h"
#import "ConstructionEventDetailInfo.h"
#import "HighwayMergeRoadRecordModel.h"
#import "HighWayRoadRecordDirectionInfoModel.h"
#import "NSDate+Addition.h"
#import "RODateHelper.h"
#import "PileInfo.h"
#import "ROImagePickViewController.h"
#import "AJPhotoPickerViewController.h"
#import "AJPhotoBrowserViewController.h"
#import "LittleVideoViewController.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "BCNetAPIClient.h"
#import "HighwayMergeRoadRecordModel.h"
#import "HighWayRoadRecordRelationInfoListModel.h"
#import "AppDelegate.h"
#import "HighWayRoadRecordDirectionInfoModel.h"
#import "StationListPopViewController.h"
#import "StationModel.h"
#import "HighWayRoadRecordDirectionInfoModel.h"
//#import "DropDownBackView.h"

@interface ComfirnDeatilController ()<UITextViewDelegate, UIPopoverPresentationControllerDelegate, LittleVideoDelegate,AJPhotoPickerProtocol,AJPhotoBrowserDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
    
    AVPlayer *_player;
    AVPlayerItem *_playItem;
    AVPlayerLayer *_playerLayer;
    AVPlayerLayer *_fullPlayer;
    BOOL _isPlaying;
}

// **************************************** -UI- ****************************************
@property (weak, nonatomic) IBOutlet UITextField *unitsLabel;         //施工单位
@property (weak, nonatomic) IBOutlet UITextField *headerTF;           //负责人
@property (weak, nonatomic) IBOutlet UITextField *contactTF;          //联系人
@property (weak, nonatomic) IBOutlet UITextField *planBeginTimeTF;    //计划开始时间
@property (weak, nonatomic) IBOutlet UITextField *planEndTimeTF;      //计划结束时间
@property (weak, nonatomic) IBOutlet UITextField *beginPileTF;        //开始桩号
@property (weak, nonatomic) IBOutlet UITextField *beginPileDistanceTF;//开始桩号距离
@property (weak, nonatomic) IBOutlet UITextField *endPileTF;          //结束桩号
@property (weak, nonatomic) IBOutlet UITextField *endPileDistanceTF;  //结束桩号距离
@property (weak, nonatomic) IBOutlet UITextField *mainLineTF;         //主线 南 北
@property (weak, nonatomic) IBOutlet UIButton    *mainLineBtn;        //主线的按钮
@property (weak, nonatomic) IBOutlet UITextField *isMianLine;         //是否是主线
@property (weak, nonatomic) IBOutlet UIButton    *isMainLineBtn;      //是否是主线按钮
@property (weak, nonatomic) IBOutlet UITextField *RoadDirectionTF;    //方向
@property (weak, nonatomic) IBOutlet UIButton *roadDirectBtn;
@property (weak, nonatomic) IBOutlet UITextView  *projectTF;          //施工项目
@property (weak, nonatomic) IBOutlet UITextView  *dealTF;             //施工处置
@property (weak, nonatomic) IBOutlet UIScrollView *imageScrollView;
@property (weak, nonatomic) IBOutlet UIView *VideoV;

@property (weak, nonatomic) IBOutlet UIButton *beginPlanTime;
@property (weak, nonatomic) IBOutlet UIButton *endPlanTime;

@property (strong, nonatomic) DateViewController *dateVC;

@property (strong, nonatomic) DropDownBackView *backView;             //下拉框

// **************************************** -请求数据- ****************************************
@property (nonatomic, strong) EventDetailModel *Model;

// **************************************** -数组- ****************************************
@property (nonatomic, strong) NSMutableArray *lineArray;//主线 南北连接线
@property (nonatomic, strong) NSArray *isMainLineArray;//是否是主线

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *dealTVHeight;

@property (nonatomic, strong) NSMutableArray *roadDirectionArray;

@property (nonatomic, strong) HighwayMergeRoadRecordModel *currentRoadModel;//当前模型

@property (nonatomic, assign) NSInteger roadIndex;

@property(nonatomic, strong) LittleVideoViewController *littleVideoVC;//拍摄小视频界面
@property (nonatomic,strong) NSURL *videoUrl;
@property(nonatomic,strong)NSMutableArray   *imageArray;
@property (nonatomic, strong) NSMutableArray *originalImgArr;

@property (strong, nonatomic) NSMutableArray *photos;

@property (nonatomic, strong) NSMutableArray *stationArray;

@property (nonatomic, strong) StationModel *stationModel; //当前选中的收费站

@end

@implementation ComfirnDeatilController

- (IBAction)ChooseImage:(UIButton *)sender {
    [self UpLoadPictures];
}
- (void) UpLoadPictures {
    if (self.originalImgArr.count >= 5) {
        [SVProgressHUD showErrorWithStatus:@"不能选择超过5张图"];
        return;
    }
    AJPhotoPickerViewController *picker = [[AJPhotoPickerViewController alloc] init];
    picker.maximumNumberOfSelection = 5;
    picker.multipleSelection        = YES;
    picker.assetsFilter             = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups          = YES;
    picker.delegate                 = self;
    picker.selectionFilter          = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        return YES;
    }];
    
    [self presentViewController:picker animated:YES completion:nil];
}

- (IBAction)CommitBtn:(id)sender {
    [self configCameraBtn];
}

-(void)configCameraBtn {
    //    [_Prompt alert:@"抱歉！暂时无法使用该功能"];
    [self cameraBtnClick];
}

- (void) cameraBtnClick {
    NSLog(@"这个照相机哦");
    LittleVideoViewController *vc = [[LittleVideoViewController alloc] init];
    vc.delegate = self;
    [self.navigationController presentViewController:vc animated:YES completion:nil];
}

#pragma mark -下拉
- (void) configDropDownData {
    // 主线 南北
    AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    for (HighwayMergeRoadRecordModel *moel in myDelegate.HighWayRoadArray) {
        [_lineArray addObject:moel.RoadName];
    }
    [_lineArray addObject:@"收费站"];
    _isMainLineArray = @[@"主线",@"非主线"];
}

- (IBAction)lineBtnChanggeClick:(id)sender {
//    NSLog(@"主线");
    __weak __typeof(self)weakSelf = self;
    AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    DrowDownViewController *directionVC = [[DrowDownViewController alloc]init];
    directionVC.view.width              = _mainLineBtn.width ;
    directionVC.dataArray               = _lineArray;
    directionVC.view.height             = 44 * (_lineArray.count);
    _backView.contentController         = directionVC;
    directionVC.indexClick              = ^(NSInteger tag, NSString *str){
        weakSelf.mainLineTF.text        = [NSString stringWithFormat:@"%@",str];
        
        if (tag == _lineArray.count - 1) { //收费站
//            AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
            StationModel *sModel = myDelegate.AllTollStationArray[0];
            _stationModel = sModel;
            for (HighwayMergeRoadRecordModel *model in myDelegate.HighWayRoadArray) {
                if ([model.RoadUID isEqualToString:sModel.RoadUID]) {
                    _currentRoadModel = model;
                }
            }
            _isMianLine.text = sModel.TollStationName;
            [self setTransDirection];
            
        }else {
        _currentRoadModel               = myDelegate.HighWayRoadArray[tag];
        [self setIsMAinline];
        }
        [_backView dismiss];
        [self refreshDirectionArray];
        [self setTransDirection];
    };
    [_backView showFrom:_mainLineBtn];
}
- (IBAction)isMianBtnClick:(id)sender {
//    NSLog(@"是否是主线");
    AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    __weak __typeof(self)weakSelf = self;
    if ([_mainLineTF.text isEqualToString:@"收费站"]) { //如果是收费站
        DrowDownViewController *stationList = [[DrowDownViewController alloc] init];
        stationList.view.width              = _isMainLineBtn.width + 10 ;
        stationList.dataArray               = _stationArray;
        stationList.view.height             = 44 * 5;
        _backView.contentController         = stationList;
        stationList.indexClick              = ^(NSInteger tag, NSString *str){
            _isMianLine.text = str;
            _stationModel    = myDelegate.AllTollStationArray[tag];
            for (HighwayMergeRoadRecordModel *roadModel in myDelegate.HighWayRoadArray) {
                if ([roadModel.RoadUID isEqualToString:_stationModel.RoadUID]) {
                    _currentRoadModel = roadModel;
                }
            }
            [self setKOrLKLabel];
            [self refreshPileNO:tag];
            [self refreshDirectionArray];
            [weakSelf.backView dismiss];
        };
        [_backView showFrom:_isMainLineBtn];

    }else{
        DrowDownViewController *directionVC = [[DrowDownViewController alloc]init];
        directionVC.view.width              = _isMainLineBtn.width + 10 ;
        directionVC.dataArray               = _isMainLineArray;
        directionVC.view.height             = 44 * (_isMainLineArray.count);
        _backView.contentController         = directionVC;
        directionVC.indexClick              = ^(NSInteger tag, NSString *str){
            weakSelf.isMianLine.text        = [NSString stringWithFormat:@"%@",str];
            [weakSelf.backView dismiss];
        };
        [_backView showFrom:_isMainLineBtn];
    }
}

- (void) refreshPileNO:(NSInteger )tag {
    AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    StationModel *model = myDelegate.AllTollStationArray[tag];
    NSInteger length    = model.PileNo.length;
    _beginPileTF.text   = [model.PileNo substringWithRange:NSMakeRange(1, length - 1)];
    _beginPileDistanceTF.text = [NSString stringWithFormat:@"%ld",(long)model.PileDistance];
    _endPileTF.text           = [model.PileNo substringWithRange:NSMakeRange(1, length - 1)];
    _endPileDistanceTF.text   = [NSString stringWithFormat:@"%ld",(long)model.PileDistance];
}

- (void) refreshDirectionArray {
    for (HighWayRoadRecordDirectionInfoModel *directionModel in _currentRoadModel.highWayRoadDirectionList) {
        [_roadDirectionArray addObject:directionModel.DirectionDescription];
    }
}

#pragma mark -联动方向
- (void) setTransDirection {
    [_roadDirectionArray  removeAllObjects];
    for (HighWayRoadRecordDirectionInfoModel *directModel in _currentRoadModel.highWayRoadDirectionList) {
        [_roadDirectionArray addObject:directModel.DirectionDescription];
    }
    _RoadDirectionTF.text = [NSString stringWithFormat:@"%@",_roadDirectionArray[0]];
}

- (void) setIsMAinline {
    _isMianLine.text = @"主线";
}

#pragma mark -默认的数据
- (void) configCurrentData {
    AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    for (HighwayMergeRoadRecordModel *highModel in myDelegate.HighWayRoadArray) {
        if ([_reportModel.RoadUID isEqualToString:highModel.RoadUID]) {
            _currentRoadModel = highModel;//获取当前的道路模型
            [self configLineTF];
        }
    }
    //配置默认的道路方向数组
    for (HighWayRoadRecordDirectionInfoModel *model in _currentRoadModel.highWayRoadDirectionList) {
        [_roadDirectionArray addObject:model.DirectionDescription];
    }
}

- (void) configLineTF {
    _mainLineTF.text = _currentRoadModel.RoadName;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.photos = [[NSMutableArray alloc] init];
    
    [self configNaviABar];
    [self requstData];
    [self setConfig];
    [self setUpArray];
    AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    for (StationModel *sModel  in myDelegate.AllTollStationArray) {
        [_stationArray addObject:sModel.TollStationName];
    }
//    [self configCurrentData];
    [self configDropDownData];
    
}

- (void) configRoadIndex {
    for (HighWayRoadRecordDirectionInfoModel *model in _currentRoadModel.highWayRoadDirectionList) {
        if ([_RoadDirectionTF.text isEqualToString:model.DirectionDescription]) {
            NSInteger ind = [_roadDirectionArray indexOfObject:model.DirectionDescription];
            _roadIndex = ind + 1;
        }
    }
}

-(UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller {
    return UIModalPresentationNone;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

- (void) setConfig {
    _Model    = [[EventDetailModel alloc] init];
    _backView = [[DropDownBackView alloc] init];
    _dealTF.delegate = self;
}
- (void) setUpArray {
    _lineArray       = [[NSMutableArray alloc] init];
    _isMainLineArray = [[NSArray alloc] init];
    _roadDirectionArray = [[NSMutableArray alloc] init];
    _stationArray   = [[NSMutableArray alloc] init];
}
#pragma mark - 导航栏
- (void) configNaviABar {
    //右边view
    UIButton *commitBtn = [[UIButton alloc] init];
    [commitBtn setTitle:@"提交" forState:UIControlStateNormal];
    commitBtn.frame         = CGRectMake(0, 0, 40, 40);
    [commitBtn addTarget:self action:@selector(commitBtnClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *commit = [[UIBarButtonItem alloc] initWithCustomView:commitBtn];
    
    UIButton *cancleBtn = [[UIButton alloc] init];
    [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
    cancleBtn.frame         = CGRectMake(0, 0, 40, 40);
    [cancleBtn addTarget:self action:@selector(cancleBtnClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *cancle = [[UIBarButtonItem alloc] initWithCustomView:cancleBtn];
    
    self.navigationItem.rightBarButtonItems = @[commit, cancle];
    //主标题
    UILabel *titleL               = [[UILabel alloc] init];
    titleL.text                   = @"未开始事件";
    titleL.frame                  = CGRectMake(0, 0, 150, 30);
    titleL.textAlignment          = NSTextAlignmentCenter;
    titleL.textColor              = [UIColor whiteColor];
    self.navigationItem.titleView = titleL;
}

- (void) cancleBtnClick {
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *CancleConstructionEventDetailInfoModel =[[RequestGinsengModel alloc] init];
    CancleConstructionEventDetailInfoModel.URL         = GetEventDataURL;
    CancleConstructionEventDetailInfoModel.MethodName  = @"StopOrCancelConstructionEvent";
    CancleConstructionEventDetailInfoModel.DataValue   = [self cancleConstructDataValueStr:self.reportModel.IncidentUID];
    CancleConstructionEventDetailInfoModel.UpdatedTime = @"";
    CancleConstructionEventDetailInfoModel.SystemCode  = @"GuangleHighway";
    requestHelper.block = ^(RequestOutginseng *requestOutginseng,id dataValueModel){
        if([requestOutginseng.Message isEqualToString:@"请求成功"]){
            [SVProgressHUD showSuccessWithStatus:@"成功取消事件"];
        }
        [self.navigationController popViewControllerAnimated:YES];
        
    };
    [requestHelper RequestGinsengModel:CancleConstructionEventDetailInfoModel andPushController:self];
}
-(NSString *)cancleConstructDataValueStr:(NSString *)IncidentUID {
    NSString *valueStr =[NSString stringWithFormat:@"[{\"key\":\"IncidentUID\",\"value\":\"%@\"}]",IncidentUID];
    return valueStr;
}
- (IBAction)beginPlanTimeBtnClick:(UIButton *)sender {
    __weak typeof(self) weakSelf=self;
    [self datePick];
    _dateVC.dateBlock=^(NSString *str){
        weakSelf.planBeginTimeTF.text=str;
    };
    [self presentViewController:_dateVC animated:YES completion:nil];
}
- (IBAction)endPlanTimeBtnClick:(UIButton *)sender {
    __weak typeof(self) weakSelf=self;
    [self datePick];
    _dateVC.dateBlock=^(NSString *str){
        weakSelf.planEndTimeTF.text=str;
    };
    [self presentViewController:_dateVC animated:YES completion:nil];
}
- (IBAction)roadDirectionBtn:(UIButton *)sender {
    [_roadDirectionArray removeAllObjects];
    [self refreshDirectionArray];
    __weak __typeof(self)weakSelf       = self;
    DrowDownViewController *directionVC = [[DrowDownViewController alloc]init];
    directionVC.view.width              = sender.width;
    directionVC.dataArray               = _roadDirectionArray;
    directionVC.view.height             = 44 * (_roadDirectionArray.count) + 10;
    _backView.contentController         = directionVC;
    directionVC.indexClick              = ^(NSInteger tag, NSString *str){
        weakSelf.RoadDirectionTF.text   = [NSString stringWithFormat:@"%@",str];
        _roadIndex  = tag + 1;
        [_backView dismiss];
    };
    [_backView showFrom:sender];
}

-(void)datePick {
    
    _dateVC=[[DateViewController alloc] init];
    _dateVC.modalPresentationStyle=UIModalPresentationPopover;
    _dateVC.popoverPresentationController.sourceView=self.view;
    _dateVC.popoverPresentationController.sourceRect=CGRectMake(self.view.center.x-56, self.view.center.y, 0, 0);
    _dateVC.popoverPresentationController.permittedArrowDirections=NO;
    _dateVC.popoverPresentationController.delegate=self;
}
- (BOOL)popoverPresentationControllerShouldDismissPopover:(UIPopoverPresentationController *)popoverPresentationController {
    return  YES;
}

#pragma mark - 提交数据
- (void) commitBtnClick {
    NSLog(@"提交");
    if (_unitsLabel.text.length < 1) {
        [SVProgressHUD showErrorWithStatus:@"施工单位不能为空"];
        return;
    }
    
    if (_headerTF.text.length < 1) {
        [SVProgressHUD showErrorWithStatus:@"现场负责人不能为空"];
        return;
    }
    
    if (_contactTF.text.length < 1) {
        [SVProgressHUD showErrorWithStatus:@"联系电话不能为空"];
        return;
    }
    
    if (_contactTF.text.length > 11) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确电话号码"];
        return;
    }
    
    if (_planBeginTimeTF.text.length < 1) {
        [SVProgressHUD showErrorWithStatus:@"计划开始时间不能为空"];
        return;
    }
    
    if (_planEndTimeTF.text.length < 1) {
        [SVProgressHUD showErrorWithStatus:@"计划结束时间不能为空"];
        return;
    }
    
    AppDelegate *mydelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    NSArray *allPileArray = mydelegate.PirArray;
    NSMutableArray *drawArray = [[NSMutableArray alloc] init];
    for (PileInfo *model in allPileArray) {
        if ([model.RoadUID isEqualToString:_currentRoadModel.RoadUID]) {     // 主干道
            [drawArray addObject:model];
        }
    }
    
    if ([_beginPileTF.text integerValue] > drawArray.count) {
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"桩号不能大于%ld",(unsigned long)drawArray.count]];
        return;
    }
    
    if (_beginPileTF.text.length < 1) {
        [SVProgressHUD showErrorWithStatus:@"开始桩号不能为空"];
        return;
    }
    
    if (_endPileTF.text.length < 1) {
        [SVProgressHUD showErrorWithStatus:@"结束桩号不能为空"];
        return;
    }
    
    if ([_endPileTF.text integerValue] > drawArray.count) {
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"桩号不能大于%ld",(unsigned long)drawArray.count]];
        return;
    }
    
    if ([_beginPileTF.text integerValue] > [_endPileTF.text integerValue]) {
        [SVProgressHUD showErrorWithStatus:@"开始桩号不能大于结束桩号"];
        return;
    }
    
    if (_mainLineTF.text.length < 1) {
        [SVProgressHUD showErrorWithStatus:@"施工地点不能为空"];
        return;
    }
    
    if (_isMianLine.text.length < 1) {
        [SVProgressHUD showErrorWithStatus:@"是否为主线不能为空"];
        return;
    }
    
    if (_RoadDirectionTF.text.length < 1) {
        [SVProgressHUD showErrorWithStatus:@"行车方向不能为空"];
        return;
    }
    
    if (_projectTF.text.length < 1) {
        [SVProgressHUD showErrorWithStatus:@"施工内容不能为空"];
        return;
    }
    
    if (!(_dealTF.text.length > 0))  {
        [SVProgressHUD showErrorWithStatus:@"施工处置不能为空"];
        return;
    }
    [self postDataToServer];
}

- (void) postDataToServer {
//    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *getCurrentEventModel=[[RequestGinsengModel alloc] init];
    getCurrentEventModel.URL=GetEventDataURL;
    getCurrentEventModel.DataValue = [self dataValueString];
    getCurrentEventModel.UpdatedTime=@"2012-01-12 12:00:00";
    getCurrentEventModel.SystemCode=@"GuangleHighway";
    getCurrentEventModel.MethodName=@"ReportConstructionEventDetailInfo";
    
//    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel){
//        
//        if ([requestOutginseng.Code integerValue]==001) {
//            [SVProgressHUD showSuccessWithStatus:@"上报成功"];
//        }
//        else
//        {
//            [SVProgressHUD showSuccessWithStatus:@"上报失败"];
//            return;
//        }
//    };
    [self requestTestUpdateImage:getCurrentEventModel Image:_originalImgArr];
}
-(void)requestTestUpdateImage:(RequestGinsengModel *)RequestGinseng Image:(NSArray *)LoadImages {
    
    [SVProgressHUD showWithStatus:@"正在上传,请稍后......"];
    
    NSDictionary *dic=[[NSDictionary alloc] init];
    dic = @{@"methodName":RequestGinseng.MethodName,@"updatedtime":RequestGinseng.UpdatedTime,@"systemcode":DefaultSystemCode,@"DataValue":RequestGinseng.DataValue};
    NSMutableArray *images = [[NSMutableArray alloc] init];
    [images addObjectsFromArray:LoadImages];
    
    //    if (LoadImages.count != 0 ) {
    [BCNetAPIClient PostVideosAndImages:GetEventDataURL parameters:dic imageArray:images videoArray:_videoUrl.absoluteString success:^(id responseObjecet) {
        [SVProgressHUD showSuccessWithStatus:@"上报成功"];
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(NSError *error) {
        [SVProgressHUD showSuccessWithStatus:@"上报失败"];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    //    }
}

- (NSString *)dataValueString {
    ConstructionEventDetailInfo *eventInfo = [[ConstructionEventDetailInfo alloc] init];
    
    eventInfo.Department        = _unitsLabel.text;
 
    eventInfo.Header            =  _headerTF.text;
    eventInfo.Telephone         = _contactTF.text;
    eventInfo.Content           = _projectTF.text;
    
    EventBaseInfo *baseModel     = [[EventBaseInfo alloc] init];
    NSString *kStr = [NSString stringWithFormat:@"K"];
  
    NSString *bStr               = [kStr stringByAppendingString:_beginPileTF.text];
    baseModel.BeginPile          = bStr;
    baseModel.BeginPileDistance  = [_beginPileDistanceTF.text integerValue];
    
    NSString *eStr = [kStr stringByAppendingString:_endPileTF.text];
    baseModel.EndPile            = eStr;
    baseModel.EndPileDistance    = [_endPileDistanceTF.text integerValue];
    
    baseModel.IncidentSource     = @"2";
    baseModel.OccurTime          = _planBeginTimeTF.text;
    baseModel.EndTime            = _planEndTimeTF.text;
    baseModel.IncidentType       = @"3";
    baseModel.IncidentParentType = @"3";
    baseModel.IncidentUID        = _reportModel.IncidentUID;
    baseModel.UpdateUserName     = _Model.EventBaseInfo.UpdateUserName;
    
    
    if ([_mainLineTF.text isEqualToString:@"收费站"]) {
        baseModel.TollStationUID    = _stationModel.TollStationUID;
        baseModel.TollStationName   = _isMianLine.text;
        baseModel.RoadUID           = _currentRoadModel.RoadUID;
        baseModel.RoadDerectionName = _RoadDirectionTF.text;
        NSLog(@"%@",_RoadDirectionTF.text);
        NSInteger roadIndex         = [_roadDirectionArray indexOfObject:_RoadDirectionTF.text];
        baseModel.RoadDerection     = [NSString stringWithFormat:@"%d",(int)roadIndex + 1];
        }else {
          baseModel.RoadUID           = _currentRoadModel.RoadUID;
          baseModel.RoadDerectionName = _RoadDirectionTF.text;
          NSInteger roadD             = [_roadDirectionArray indexOfObject:baseModel.RoadDerectionName];
          baseModel.RoadDerection     = [NSString stringWithFormat:@"%d",(int)roadD + 1];
          baseModel.TollStationName = nil;
          baseModel.TollStationUID  = nil;
    }
    NSDate *now = [RODateHelper localeDate];
    NSString *dateStr = [RODateHelper dateToString:now withFormat:nil];
    baseModel.UpdateTime         = dateStr;
//    baseModel.RoadDerection      = [NSString stringWithFormat:@"%ld",(long)_roadIndex];
//    baseModel.RoadName           = _mainLineTF.text;
    baseModel.ETCExitCount       = _Model.EventBaseInfo.ETCExitCount;
    baseModel.RoadDerectionName  = _RoadDirectionTF.text;
    baseModel.IncidentSource     = [NSString stringWithFormat:@"%d",2];
    baseModel.IncidentDetail     = _dealTF.text;
    baseModel.DealDetail         = _dealTF.text;
    baseModel.RoadUID            = _currentRoadModel.RoadUID;
    baseModel.ETCExitCount       = _Model.EventBaseInfo.ETCExitCount;
    baseModel.SystemUID          = _Model.EventBaseInfo.SystemUID;
    baseModel.State              = _Model.EventBaseInfo.State;
    baseModel.IncidentLevel      = _Model.EventBaseInfo.IncidentLevel;
    baseModel.RecordUserUID      = _Model.EventBaseInfo.RecordUserUID;
    baseModel.RecordUserName     = _Model.EventBaseInfo.RecordUserName;
    baseModel.ActualEndTime      = nil;
    baseModel.RecordTime         = _Model.EventBaseInfo.RecordTime;
    baseModel.SystemCode         = _Model.EventBaseInfo.SystemCode;
    baseModel.IncidentTypeName   = _Model.EventBaseInfo.IncidentTypeName;
    baseModel.IncidentDetail     = _dealTF.text;
    eventInfo.EventBaseInfo      = baseModel;
    NSLog(@"%@ %@",baseModel.RoadDerectionName, _RoadDirectionTF.text);
    
    EventDealList *listModel = [[EventDealList alloc] init];
    listModel.DealDetail     = _dealTF.text;
    listModel.IncidentUID    = _reportModel.IncidentUID;
    listModel.DealTime       = dateStr;
    eventInfo.EventDealList  = @[listModel];
    
    NSMutableDictionary *dic = eventInfo.mj_keyValues;
    NSString *json           = [dic mj_JSONString];
    
    ParModel *model = [[ParModel alloc] init];
    model.key       = @"ConstructionEventDetailInfo";
    model.value     = json;
    
    NSMutableDictionary *ModelDic = model.mj_keyValues;
    NSString *dataValue  = [ModelDic mj_JSONString];
    NSString *str        = @"[";
    NSString *temp       = [str stringByAppendingString:dataValue];
    NSString *str1       = @"]";
    NSString *JsonString = [temp stringByAppendingString:str1];
    NSLog(@"Jsonstring%@",JsonString);
    return JsonString;
}

#pragma mark - 请求数据
- (void) requstData {
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *GetConstructionEventDetailInfo = [[RequestGinsengModel alloc] init];
    GetConstructionEventDetailInfo.URL         = GetEventDataURL;
    GetConstructionEventDetailInfo.DataValue   = [self getConstructDataValueStr:self.reportModel.IncidentUID];
    GetConstructionEventDetailInfo.UpdatedTime = @"";
    GetConstructionEventDetailInfo.SystemCode  = @"GuangleHighway";
    GetConstructionEventDetailInfo.MethodName  = @"GetConstructionEventDetailInfo";
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel){
        _Model = [EventDetailModel mj_objectWithKeyValues:requestOutginseng.DataValue];
        [self getCurrentHighWayRoadModel];
        [self refreshUIData];
        [self configRoadIndex];
    };
    [requestHelper RequestGinsengModel:GetConstructionEventDetailInfo andPushController:self];
}

- (void) getCurrentHighWayRoadModel { //获取返回来的道路模型
    AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    for (HighwayMergeRoadRecordModel *roadModel in myDelegate.HighWayRoadArray) {
        if ([roadModel.RoadUID isEqualToString:_Model.EventBaseInfo.RoadUID]) {
            _currentRoadModel = roadModel;
        }
    }
}


#pragma mark - 加载数据
- (void) refreshUIData {
    _unitsLabel.text            = _Model.Department;
    _headerTF.text              = _Model.Header;
    _contactTF.text             = _Model.Telephone;
    
    NSString *b              = [NSString stringWithFormat:@"%@",_Model.EventBaseInfo.BeginPile];
    NSString *begin          = [b stringByReplacingOccurrencesOfString:@"K" withString:@""];
    NSString *beginDistance  = [NSString stringWithFormat:@"%ld",(long)_Model.EventBaseInfo.BeginPileDistance];
   
    [self setKOrLKLabel];
    
    NSString *e                 = _Model.EventBaseInfo.EndPile;
    NSString *end               = [e stringByReplacingOccurrencesOfString:@"K" withString:@""];
    NSString *endDistance       = [NSString stringWithFormat:@"%ld",(long)_Model.EventBaseInfo.EndPileDistance];
    
    _beginPileTF.text           = begin;
    _beginPileDistanceTF.text   = beginDistance;
    _endPileTF.text             = end;
    _endPileDistanceTF.text     = endDistance;
    
    _planBeginTimeTF.text       = _Model.EventBaseInfo.OccurTime;
    _planEndTimeTF.text         = _Model.EventBaseInfo.EndTime;
    _projectTF.text             = _Model.Content;
    _RoadDirectionTF.text       = _Model.EventBaseInfo.RoadDerectionName;
    
    if (_Model.EventBaseInfo.TollStationUID ) {
        AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        _mainLineTF.text = @"收费站";
        for (StationModel *model in myDelegate.AllTollStationArray) {
            if ([model.TollStationUID isEqualToString:_Model.EventBaseInfo.TollStationUID]) {
                _isMianLine.text = model.TollStationName;
            }
        }
        for (HighwayMergeRoadRecordModel *highModel in myDelegate.HighWayRoadArray) {
            if ([highModel.RoadUID isEqualToString:_Model.EventBaseInfo.RoadUID]) {
                _currentRoadModel = highModel;
            }
        }
//        [self setTransDirection];
    }else {
        _mainLineTF.text            = _Model.EventBaseInfo.RoadName;
        if (_Model.EventBaseInfo.IsRamp == 0) {
            _isMianLine.text = @"主线";
        }else {
            _isMianLine.text  = @"非主线";
        }
    }
}

- (void) setKOrLKLabel{
    if ([_currentRoadModel.RoadUID isEqualToString:@"8dd13d88-cb02-4471-876b-1dfe39419ee6"]) {
        UILabel *lab1      = [[UILabel alloc] init];
        lab1.text                 = @"K";
        lab1.frame                = CGRectMake(0, 0, 15, 10);
        lab1.textAlignment        = NSTextAlignmentCenter;
        _beginPileTF.leftView     = lab1;
        _beginPileTF.leftViewMode = UITextFieldViewModeAlways;
        
        UILabel *lab2      = [[UILabel alloc] init];
        lab2.text               = @"K";
        lab2.frame              = CGRectMake(0, 0, 15, 10);
        lab2.textAlignment      = NSTextAlignmentCenter;
        _endPileTF.leftView     = lab2;
        _endPileTF.leftViewMode = UITextFieldViewModeAlways;
        
    } else {
        UILabel *lab1      = [[UILabel alloc] init];
        lab1.font          = [UIFont boldSystemFontOfSize:15];
        lab1.text                 = @"LK";
        lab1.frame                = CGRectMake(0, 0, 25, 10);
        lab1.textAlignment        = NSTextAlignmentCenter;
        _beginPileTF.leftView     = lab1;
        _beginPileTF.leftViewMode = UITextFieldViewModeAlways;
        
        UILabel *lab2      = [[UILabel alloc] init];
        lab2.font          = [UIFont boldSystemFontOfSize:15];
        lab2.text               = @"LK";
        lab2.frame              = CGRectMake(0, 0, 25, 10);
        lab2.textAlignment      = NSTextAlignmentCenter;
        _endPileTF.leftView     = lab2;
        _endPileTF.leftViewMode = UITextFieldViewModeAlways;
    }

}

#pragma mark - BoPhotoPickerProtocol
- (void)photoPickerDidCancel:(AJPhotoPickerViewController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)photoPicker:(AJPhotoPickerViewController *)picker didSelectAssets:(NSArray *)assets {
    [self.photos addObjectsFromArray:assets];
    [picker dismissViewControllerAnimated:NO completion:nil];
    CGFloat x = 0;
    CGRect frame = CGRectMake(0, 0, 125, 125);
    self.imageScrollView.hidden = NO;
    
    if (_originalImgArr.count > 0) {
        [_originalImgArr removeAllObjects];
    }
    _originalImgArr = [[NSMutableArray alloc] init];
    for (int i = 0 ; i < self.photos.count; i++) {
        ALAsset *asset = self.photos[i];
        UIImage *tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        frame.origin.x = x;
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
        [imageView setContentMode:UIViewContentModeScaleAspectFill];
        imageView.clipsToBounds = YES;
        imageView.image = tempImg;
        imageView.tag = i;
        imageView.userInteractionEnabled = YES;
        [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showBig:)]];
        [_originalImgArr addObject:imageView.image];
        [self.imageScrollView addSubview:imageView];
        x += frame.size.width+5;
        self.imageScrollView.contentSize = CGSizeMake(125 * self.photos.count, 0);
    }
}

- (void)showBig:(UITapGestureRecognizer *)sender {
    NSInteger index = sender.view.tag;
    AJPhotoBrowserViewController *photoBrowserViewController = [[AJPhotoBrowserViewController alloc] initWithPhotos:self.photos index:index];
    photoBrowserViewController.delegate = self;
    [self presentViewController:photoBrowserViewController animated:YES completion:nil];
}
- (void)photoBrowser:(AJPhotoBrowserViewController *)vc didDonePhotos:(NSArray *)photos {
    [vc dismissViewControllerAnimated:YES completion:nil];
}

- (void)photoPickerTapCameraAction:(AJPhotoPickerViewController *)picker {
    [self checkCameraAvailability:^(BOOL auth) {
        if (!auth) {
            NSLog(@"没有访问相机权限");
            return;
        }
        [picker dismissViewControllerAnimated:NO completion:nil];
        UIImagePickerController *cameraUI = [UIImagePickerController new];
        cameraUI.allowsEditing   = NO;
        cameraUI.delegate        = self;
        cameraUI.sourceType      = UIImagePickerControllerSourceTypeCamera;
        cameraUI.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
        [self presentViewController: cameraUI animated: YES completion:nil];
    }];
}
- (void)checkCameraAvailability:(void (^)(BOOL auth))block {
    BOOL status = NO;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(authStatus == AVAuthorizationStatusAuthorized) {
        status = YES;
    } else if (authStatus == AVAuthorizationStatusDenied) {
        status = NO;
    } else if (authStatus == AVAuthorizationStatusRestricted) {
        status = NO;
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(granted){
                if (block) {
                    block(granted);
                }
            } else {
                if (block) {
                    block(granted);
                }
            }
        }];
        return;
    }
    if (block) {
        block(status);
    }
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    UIImage *originalImage;
    if (CFStringCompare((CFStringRef) mediaType,kUTTypeImage, 0)== kCFCompareEqualTo) {
        originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        UIImageWriteToSavedPhotosAlbum(originalImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo {
    if (!error) {
        NSLog(@"保存到相册成功");
        AJPhotoPickerViewController *picker = [[AJPhotoPickerViewController alloc] init];
        picker.maximumNumberOfSelection = 5;
        picker.multipleSelection        = YES;
        picker.assetsFilter             = [ALAssetsFilter allPhotos];
        picker.showEmptyGroups          = YES;
        picker.delegate                 = self;
        picker.selectionFilter          = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
            return YES;
        }];
        [self dismissViewControllerAnimated:NO completion:nil];
        [self presentViewController:picker animated:NO completion:nil];
    }else{
        NSLog(@"保存到相册出错%@", error);
    }
}

// *********** - 播放小视频 - *************
#pragma mark -littleVideoDelegate
- (void)finishLittleVideoViewControllerCapture:(NSURL *)filePath {
    _videoUrl = filePath;
    [self crreatPlayViedeo:filePath];
    
}
- (void) crreatPlayViedeo:(NSURL *)videoUrl {
    _playItem = [AVPlayerItem playerItemWithURL:videoUrl];
    _player = [AVPlayer playerWithPlayerItem:_playItem];
    _playerLayer =[AVPlayerLayer playerLayerWithPlayer:_player];
    _playerLayer.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width - 16, 200);
    _playerLayer.videoGravity=AVLayerVideoGravityResizeAspectFill;//视频填充模式
    [self.VideoV.layer addSublayer:_playerLayer];
    [_player play];
//    _isHaveVideo   = YES;
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_player pause];
    _player = nil;
//    [_sheet hiddenSheet];
}

-(float) heightForTextView: (UITextView *)textView WithText: (NSString *) strText{
    CGSize constraint = CGSizeMake(textView.contentSize.width , CGFLOAT_MAX);
    CGRect size = [strText boundingRectWithSize:constraint
                                        options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                     attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:15]}
                                        context:nil];
    float textHeight = size.size.height + 22.0;
    return textHeight;
}



//IncidentUID拼接参数
-(NSString *)getConstructDataValueStr:(NSString *)IncidentUID {
    NSString *valueStr =[NSString stringWithFormat:@"[{\"key\":\"EventUID\",\"value\":\"%@\"}]",IncidentUID];
    return valueStr;
}
@end
